package com.visionork.android.twe.parser;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.visionork.android.twe.activity.Episode;

public class EpisodeAdapterImpl implements EpisodeAdapter {
	private String _episode_url;
	private static final String PREFIX = "http://www.youtube.com/v/";

	public EpisodeAdapterImpl(String episode_url) {
		_episode_url = episode_url;
	}

	@Override
	public ArrayList<Episode> get_episode_list() {
		ArrayList<Episode> episode_list = new ArrayList<Episode>();
		int section = 0;
		Episode previous_episode = null;
		while (true) {
			section++;
			String url_string = _episode_url;
			if (section > 1) {
				url_string = url_string + section;
			}			
			Episode episode = null;
			try {
				String title = "Part " + section;
				episode = get_episode_section(title, url_string);				
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (episode != null && previous_episode == null || episode != null && !episode.get_id().equals(previous_episode.get_id())) {				
				episode_list.add(episode);
				previous_episode = episode;
			} else {
				break;
			}
		}

		return episode_list;
	}

	private Episode get_episode_section(String title, String url_string)
			throws MalformedURLException, IOException {
		URL url = new URL(url_string);
		Document doc = Jsoup.parse(url, 5000);

		Elements elms = doc.getElementsByTag("embed");
		for (Element elm : elms) {
			if (elm.hasAttr("src") && elm.attr("src").startsWith(PREFIX)) {
				return new Episode(title, get_youtube_id(elm.attr("src")));
			}
		}

		return null;
	}

	private String get_youtube_id(String urlString) {
		String id = "";
		Pattern r = Pattern.compile("http://www.youtube.com/v/([^\\?]*)\\?");
		Matcher m = r.matcher(urlString);
		if (m.find()) {
			id = m.group(1);
		}

		return id;
	}
}
